package com.wryyyyy.utils;

import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.springframework.core.io.Resource;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.ResourceRegionHttpMessageConverter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class GridFsResourceHttpRequestHandler extends ResourceHttpRequestHandler {
    private final GridFSFile file;
    private final GridFSDownloadStream stream;

    public GridFsResourceHttpRequestHandler(GridFSFile file, GridFSDownloadStream stream) {
        this.file = file;
        this.stream = stream;
        // 这两行代码必须有 否则会报 Not initialized 错误
        this.setResourceRegionHttpMessageConverter(new ResourceRegionHttpMessageConverter());
        this.setResourceHttpMessageConverter(new ResourceHttpMessageConverter());
    }

    @Override protected Resource getResource(HttpServletRequest request) throws IOException {
        return new GridFsResource(file,stream);
    }
}
